package com.liliudong.pinkyponk.api.admin.utils;

import com.liliudong.pinkyponk.api.admin.security.UserDetailsImpl;
import com.liliudong.pinkyponk.biz.sys.entity.SysUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Objects;
import java.util.Optional;
import java.util.Set;

/**
 * SecurityHelper
 *
 * @author liliudong
 * @date 2022-06-02 23:27
 **/
public class SecurityHelper {

    public static Optional<UserDetailsImpl> getUserDetails() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (Objects.isNull(authentication)) {
            return Optional.empty();
        }
        return authentication.getPrincipal() instanceof UserDetailsImpl
                ? Optional.of((UserDetailsImpl) authentication.getPrincipal()) : Optional.empty();
    }

    public static Optional<SysUser> getCurrentUser() {
        Optional<UserDetailsImpl> optional = getUserDetails();
        if (optional.isEmpty()) {
            return Optional.empty();
        }
        return Optional.of(optional.get().getSysUser());
    }

    public static Optional<Set<Integer>> getDataScopes() {
        Optional<UserDetailsImpl> optional = getUserDetails();
        if (optional.isEmpty()) {
            return Optional.empty();
        }
        return Optional.of(optional.get().getDataScopes());
    }

    public static Optional<String> getCurrentOrgNo() {
        Optional<UserDetailsImpl> optional = getUserDetails();
        if (optional.isEmpty()) {
            return Optional.empty();
        }
        return Optional.of(optional.get().getCurrentOrgNo());
    }

    public static Optional<Set<String>> getOrgNos() {
        Optional<UserDetailsImpl> optional = getUserDetails();
        if (optional.isEmpty()) {
            return Optional.empty();
        }
        return Optional.of(optional.get().getOrgNos());
    }

}
